TMDB_API_KEY = '8aeb5a7297286d39e8f93e4563a8bc78'
TMDB_SEARCH = 'http://api.themoviedb.org/2.1/Movie.search/'
TMDB_INFO   = 'http://api.themoviedb.org/2.1/Movie.getInfo/'
TRAZAS = False

def Start():
	HTTP.CacheTime = CACHE_1HOUR * 4

def removeNone(ListyList):
	try: 
		ListyList.remove(None)
	except: 
		pass
def LogInfo(traza):
	if TRAZAS:
		Log(traza)
		
class TMDbStandaloneAgent(Agent.Movies):
	name = 'TheMovieDB Agente'
	languages = [Locale.Language.Spanish, Locale.Language.English]
	primary_provider = True
	accepts_from = ['com.plexapp.agents.localmedia']

	def search(self, results, media, lang):
		LogInfo('Media name: ' + media.name)
		LogInfo('Lang: ' + lang)
		shipping_name = media.name.replace(' ','%20')
		'http://api.themoviedb.org/2.1/Movie.search/es/xml/8aeb5a7297286d39e8f93e4563a8bc78/nombrepelicula'
		url = TMDB_SEARCH + lang + '/xml/' + TMDB_API_KEY + '/' + shipping_name
		LogInfo('urlsearch: ' + url)
		search_results = XML.ElementFromURL(url)
		mine = []
		for item in search_results.xpath('//movie'):
			score_penalty = 0
			try: 
				year = int(item.xpath('released')[0].text[:4])
			except: 
				year = 0
			if year and media.year:
				score_penalty += abs(int(media.year) - year)*3
			if item.xpath('type')[0].text != 'movie':
				score_penalty += 50
			allnames = sorted(set([item.xpath('name')[0].text, item.xpath('original_name')[0].text, item.xpath('alternative_name')[0].text]))
			removeNone(allnames)
			scorednames = sorted([(Util.LevenshteinDistance(media.name, theirname), theirname) for theirname in allnames])
			if scorednames:
				name = scorednames[0][1]
				score_penalty += scorednames[0][0]
				score = 100-score_penalty
				id = item.xpath('id')[0].text
				results.Append(MetadataSearchResult(id=id, name=name, year=year, score=score, lang=lang))
				mine.append((name,year,score))  

				

	def update(self, metadata, media, lang): 
		proxy = Proxy.Preview
		
		def GetText(tag):
			info = movie_elem.xpath(tag)[0].text
			if info in [None, 'No overview found.', 'None']:
				info = ''
			LogInfo('Clave: ' + tag + ' valor: ' + info )
			return info
			
		metadata.title = media.title			
		LogInfo(metadata.title + ' (' + str(metadata.year) + ')')
		'http://api.themoviedb.org/2.1/Movie.getInfo/es/xml/8aeb5a7297286d39e8f93e4563a8bc78/idpelicula'
		url = TMDB_INFO + lang + '/xml/' + TMDB_API_KEY + '/' +  metadata.id
		LogInfo('urlinfo: ' + url)
		movie_info = XML.ElementFromURL(url)
		movie_elem = movie_info.xpath('//movies/movie')[0]
		metadata.summary = GetText('overview')
		release_date = GetText('released')
		if release_date != '':
			metadata.year = int(release_date[:4])
			metadata.originally_available_at = Datetime.ParseDate(release_date).date()
		tagline = GetText('tagline')
		try:
			first_studio = movie_elem.xpath('studios/studio')[0]
			metadata.studio = first_studio.xpath('@name')[0]
		except:
			pass
		metadata.rating = float(GetText('rating'))
		metadata.content_rating = GetText('certification')
		metadata.directors.clear()
		metadata.writers.clear()
		metadata.roles.clear()
		for person in movie_elem.xpath('cast/person'):
			try:
				name = person.xpath('@name')[0]
				job = person.xpath('@job')[0]
				if job == 'Actor':
					character = person.xpath('@character')[0]
					role = metadata.roles.new()
					role.role = character
					role.actor = name
				elif job == 'Director':
					metadata.directors.add(name)
				elif job in ['Screenplay', 'Author', 'Writer']:
					metadata.writers.add(name)
			except:
				pass
		# genero
		metadata.genres.clear()
		for category in movie_elem.xpath('categories/category'):
			try:
				type = category.xpath('@type')[0]
				nombre = category.xpath('@name')[0]
				LogInfo('Type: ' + type + ' nombre: ' + nombre )
				if type == 'genre':
					metadata.genres.add(nombre)
			except:
				pass
				
		#Paises de rodaje
		metadata.countries.clear()
		for country in movie_elem.xpath('countries/country'):
			try:
				nombre = country.xpath('@name')[0]
				metadata.countries.add(nombre)
			except:
				pass
		
		# poster
		img_sort = 0
		for poster_elem in movie_elem.xpath('images/image[@type="poster" and @size="original"]'):
			img_sort += 1
			poster_url = poster_elem.xpath('@url')[0]
			thumb_url = poster_url.replace('-original.','-thumb.')
			thumb = HTTP.Request(thumb_url)
			try: 
				metadata.posters[poster_url] = proxy(thumb, sort_order = img_sort)
			except: 
				pass
			
		# fan art / backdrops				
		img_sort = 0		
		for backdrop_elem in movie_elem.xpath('images/image[@type="backdrop" and @size="original"]'):
			img_sort += 1
			backdrop_url = backdrop_elem.xpath('@url')[0]
			thumb_url = backdrop_url.replace('-original.','-thumb.')
			thumb = HTTP.Request(thumb_url)
			try: 
				metadata.art[backdrop_url] = proxy(thumb, sort_order = img_sort)
			except: 
				pass	
		
		

		
